<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      title="部门列表"
      toolbar
      search
      ref="asyncExpandTreeRef"
      :clickRowToExpand="false"
      defaultExpandAll
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    />
    <Loading
        :loading="loading"
        :absolute="absolute"
        :theme="theme"
        :background="background"
        :tip="tip"
      />
  </div>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onMounted, ref, unref } from 'vue';

  import { BasicTree, TreeItem,TreeActionType } from '@/components/Tree';
  import { getDeptList } from '@/api/system/dept';
  import { Loading,useLoading } from '@/components/Loading';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree,Loading },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
      const [openFullLoading, closeFullLoading] = useLoading({
        tip: '加载中...',
      });
      async function fetch() {
          openFullLoading()
          const treeapidata = await getDeptList(null);
          var dept_data = treeapidata.data
          dept_data =await convertKey(dept_data)
          treeData.value = ( dept_data) as any as TreeItem[];
          nextTick(() => {
            unref(asyncExpandTreeRef)?.expandAll(true);
          });
          closeFullLoading()
        // treeData.value = (await getDeptList()) as unknown as TreeItem[];
      }

      function handleSelect(keys) {
        emit('select', keys[0]);
      }
      async function convertKey(menulist) {
          if (!menulist) return null;
          for (const map of menulist) {
            map['title'] = map.name
            map['key'] = map.id
            // map['icon'] = map.icon
            if (map.children != undefined && map.children.length > 0) {
                var childrenList =await convertKey(map.children);
                map["children"]= childrenList;
            }
        }
        return menulist
      }
      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect,asyncExpandTreeRef,openFullLoading,closeFullLoading };
    },
  });
</script>
